function storeUserDetails(data) {
    try {
        if (data && data.data) {
            localStorage.setItem('uname',data.data.username);
            localStorage.setItem('token', data.data.token);
        } else {
            console.error('Invalid server response structure');
        }
    } catch (error) {
        console.error('Failed to set localStorage items:', error);
    }
}

async function getMsg(username, password) {
    try {
        let res = await axios({
            url: '/login',
            method: 'POST',
            data: { username: username, password: password }
        });

        let data = res.data;
        storeUserDetails(data);

        pxmu.toast({
            msg: '登陆成功',
            time: 2500,
            bg: 'rgba(0, 0, 0, 0.86)',
            color: '#fff',
            location: 'top',
            animation: 'slidedown',
            type: 'pc',
            status: 'success'
        });

        location.href = './index.html';

    } catch (err) {
        pxmu.fail('账号或密码错误');
        throw err; // 重新抛出错误以便被外层catch捕获
    }
}

document.querySelector('#btn-login').addEventListener('click', async function (e) {
    e.preventDefault();

    // 获取最新的表单数据
    let username = document.querySelector('#input-email').value.trim();
    let password = document.querySelector('#input-password').value.trim();

    // 检查输入是否为空
    if (!username || !password) {
        pxmu.fail({
            msg: '用户名和密码不能为空',
            time: 2500,
            bg: 'rgba(0, 0, 0, 0.65)',
            color: '#fff',
            animation: 'fade',
            close: true,
            inscroll: false,
            inscrollbg: 'rgba(0, 0, 0, 0.45)',
        });
        return;
    }

    const nameReg = /^[a-zA-Z0-9]{8,30}$/;
    const wordReg = /^[a-zA-Z0-9]{6,30}$/;

    // 用户名校验
    if (!nameReg.test(username)) {
        pxmu.fail({
            msg: '用户名须由8-30位的字母或数字组成',
            time: 2500,
            bg: 'rgba(0, 0, 0, 0.65)',
            color: '#fff',
            animation: 'fade',
            close: true,
            inscroll: false,
            inscrollbg: 'rgba(0, 0, 0, 0.45)',
        });
        return;
    }

    // 密码校验
    if (!wordReg.test(password)) {
        pxmu.fail({
            msg: '密码须由6-30位的字母或数字组成',
            time: 2500,
            bg: 'rgba(0, 0, 0, 0.65)',
            color: '#fff',
            animation: 'fade',
            close: true,
            inscroll: false,
            inscrollbg: 'rgba(0, 0, 0, 0.45)',
        });
        return;
    }

    // 禁用按钮以防止重复提交
    let btnLogin = document.querySelector('#btn-login');
    btnLogin.disabled = true;

    try {
        await getMsg(username, password);
    } catch (err) {
        // 如果有错误发生，重新启用按钮
        btnLogin.disabled = false;
    }
});